package com.wd.base.router;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.fragment.app.Fragment;

import com.wd.base.config.Constance;
import com.wd.base.util.Logger;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dalvik.system.DexFile;

/**
 * NA<BR>
 *
 * @author w4425
 * @version [V2.0.0, 2021/4/20]
 * @since V1.0.0
 */
public class ARouter {
    private static String TAG = "Router";
    private static volatile ARouter mInstance = new ARouter();
    private WeakReference<Context> reference;
    private String path;
    private static String ROUTER_PACKAGE = "com.wd.test";
    private Map<String, Class<? extends Activity>> map = new HashMap<>();

    public void init(Application application) {
        mInstance.reference = new WeakReference<>(application);
        if (Constance.isRouterAnnotation) {
            List<String> className = getAllActivity(ROUTER_PACKAGE);
            for (String cls : className) {
                try {
                    Class<?> aClass = Class.forName(cls);
                    if (IRouter.class.isAssignableFrom(aClass)) {
                        IRouter iRouter = (IRouter) aClass.newInstance();
                        iRouter.addActivity();
                    }
                } catch (Exception e) {
                    Logger.w("init e = " + e.fillInStackTrace());
                }
            }
        }
    }

    public static Map<String, Class<? extends Activity>> getMap() {
        return mInstance.map;
    }

    public static synchronized ARouter getInstance() {
        return mInstance;
    }

    public void addActivity(String name, Class clazz) {
        Logger.w(TAG, "addActivity ,name= " + name + ";activity =" + clazz);
        if (getMap() != null && !TextUtils.isEmpty(name) && clazz != null) {
            getMap().put(name, clazz);
        }
    }

    public ARouter build(String path) {
        mInstance.path = path;
        return mInstance;
    }

    public void navigation(Context context) {
        if (mInstance.map != null) {
            Log.e(TAG, "className = " + mInstance.path);
            Class<? extends Activity> activity = mInstance.map.get(mInstance.path);
            if (activity != null) {
                context.startActivity(new Intent(context, activity));
            }
        }
    }

    public void navigation(Context context, Bundle bundle) {
        if (mInstance.map == null) {
            Log.e(TAG, "mInstance.map == null");
            return;
        }
        Log.e(TAG, "path = " + mInstance.path + ";map.size = " + map.size());

        for (Map.Entry<String, Class<? extends Activity>> m : mInstance.map.entrySet()) {
            Log.d(TAG, "key = " + m.getKey());
            Log.i(TAG, "value = " + m.getValue());
        }

        Class<? extends Activity> activity = mInstance.map.get(mInstance.path);
        if (activity == null) {
            Log.e(TAG, "activity == null");
            return;
        }
        Intent intent = new Intent(context, activity);
        if (bundle != null) {
            intent.putExtra("message", bundle);
        }
        context.startActivity(intent);
        mInstance.path = "";
    }

    public void navigation(Fragment fragment, Bundle bundle, int requestCode) {
        if (mInstance.map == null) {
            Log.e(TAG, "mInstance.map == null");
            return;
        }
        Log.e(TAG, "className = " + mInstance.path);
        Class<? extends Activity> activity = mInstance.map.get(mInstance.path);
        if (activity == null) {
            Log.e(TAG, "routeMeta == null");
            return;
        }
        Intent intent = new Intent(fragment.getActivity(), activity);
        if (bundle != null) {
            intent.putExtra("message", bundle);
        }
        fragment.startActivityForResult(intent, requestCode);
    }

    public void navigationResult(Activity activity, Bundle bundle) {
        if (mInstance.map == null) {
            Log.e(TAG, "mInstance.map == null");
            return;
        }
        Log.e(TAG, "className = " + mInstance.path);
        Class<? extends Activity> aClass = mInstance.map.get(mInstance.path);
        if (activity == null) {
            Log.e(TAG, "routeMeta == null");
            return;
        }
        Intent intent = new Intent(activity, aClass);
        if (bundle != null) {
            intent.putExtra("message", bundle);
        }
        activity.setResult(Activity.RESULT_OK, intent);
    }

    /**
     * 获取所有activity
     *
     * @param packageName
     * @return
     */
    public List<String> getAllActivity(String packageName) {
        List<String> list = new ArrayList<>();
        String path;
        Context context = reference.get();
        if (context == null) {
            Logger.w("getAllActivityUtils context == null");
            return list;
        }
        try {
            path = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
            DexFile dexFile = new DexFile(path);
            Enumeration enumeration = dexFile.entries();
            while (enumeration.hasMoreElements()) {
                String name = (String) enumeration.nextElement();
                if (name.contains(packageName)) {
                    list.add(name);
                }
            }
        } catch (Exception e) {
            Logger.w("getAllActivityUtils e = " + e.fillInStackTrace());
        }
        return list;
    }

}
